import os
import tempfile
from fastapi import UploadFile
import logging

logger = logging.getLogger(__name__)

def save_temp_file(file: UploadFile) -> str:
    """
    将上传的文件保存到临时目录
    
    Args:
        file (UploadFile): 上传的文件对象
        
    Returns:
        str: 临时文件的完整路径
        
    Raises:
        Exception: 如果文件保存失败
    """
    try:
        # 使用更安全的临时文件生成方式
        suffix = os.path.splitext(file.filename)[1]
        with tempfile.NamedTemporaryFile(delete=False, suffix=suffix) as temp_file:
            content = file.file.read()
            temp_file.write(content)
            temp_path = temp_file.name
            
        # 重置文件指针，以便后续可能的读取
        file.file.seek(0)
        
        logger.info(f"临时文件已保存: {temp_path}")
        return temp_path
        
    except Exception as e:
        logger.error(f"保存临时文件失败: {str(e)}")
        raise Exception(f"保存临时文件失败: {str(e)}")
